package utils;

/**
 * Created by fanzhenyu02 on 2020/2/14.
 */

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.swing.filechooser.FileSystemView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;


public class FileProcessUtil {


    public static void run_analysis_bizMerchantNo() {
        Map<String, StringBuilder> map = new TreeMap<>();
        String line = null;
        try {
            FileInputStream inputStream = new FileInputStream("/Users/vonmax/Downloads/paygate_info.log-2020-05-22-2.log");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            while ((line = bufferedReader.readLine()) != null) {
                try {
                    String traceId = line.split("__traceId__=")[1].split("}#")[0];
                    if (map.containsKey(traceId)) {
                        StringBuilder builder = map.get(traceId);
                        builder.append(line).append("\n");
                    } else {
                        StringBuilder builder = new StringBuilder();
                        builder.append(line).append("\n");
                        map.put(traceId, builder);
                    }
                } catch (Exception e) {
                    //System.out.println("Skipp line :"+line);
                }
            }

//            FileOutputStream outputStream = new FileOutputStream("/Users/vonmax/Downloads/logMap.txt");
//            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
//            bufferedWriter.write(map.toString());
//            outputStream.close();
//            bufferedWriter.close();


            Map<String, Set<String>> bizMap = new TreeMap<>();
            for (Map.Entry<String, StringBuilder> entry : map.entrySet()) {
                String logContent = entry.getValue().toString();
                try {
                    String key = logContent.split("验签字符串为:")[1].split("2020-")[0];
                    if (logContent.contains("bizMerchantNo=")) {
                        key = logContent.split("bizMerchantNo=")[1].split("&")[0];
                    }
                    String appId = getAppIdFromLog(logContent);

                    if (bizMap.containsKey(key)) {
                        bizMap.get(key).add(appId);
                    } else {
                        Set<String> appIdSet = new HashSet<>();
                        appIdSet.add(appId);
                        bizMap.put(key, appIdSet);
                    }
                } catch (Exception ex) {
                    System.out.println("Exception parse traceId: " + entry.getKey());
//                    System.out.println("error parse log: " + logContent);
                }
            }

            System.out.println("开始打印map\n\n");
            printMap(bizMap, "analysis.txt");

            //close stream
            inputStream.close();
            bufferedReader.close();
        } catch (Exception e) {
            System.out.println(line);
            e.printStackTrace();
        }
    }

    public static String getAppIdFromLog(String logContent) {
        String appId = "";

        // method 1
        try {
            appId = logContent.split("\"appid\":\"")[1].split("\",\"")[0];
        } catch (Exception e) {

        }
        if (StringUtils.isNotBlank(appId)) {
            return appId;
        }

        // method 2
        try {
            appId = logContent.split("<appid><!")[1].split("]]>")[0].split("CDATA\\[")[1];
        } catch (Exception e) {

        }
        if (StringUtils.isNotBlank(appId)) {
            return appId;
        }

        // method 3
        try {
            appId = logContent.split("appid")[1].split(",|&")[0];
            appId = appId.substring(appId.indexOf("wx"));
        } catch (Exception e) {

        }
        if (StringUtils.isNotBlank(appId)) {
            return appId;
        }


        return appId;
    }


    public static void printMap(Map<String, Set<String>> resMa, String fileName) throws Exception {
        FileOutputStream outputStream = new FileOutputStream("/Users/vonmax/Downloads/" + fileName);
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));

        for (Map.Entry<String, Set<String>> entry : resMa.entrySet()) {
//            if (!entry.getKey().contains("=") && !entry.getKey().contains("&")) {
//                System.out.println("--------------------------------------------------------");
//                System.out.println(entry.getKey() + " -> value: " + entry.getValue().toString());
//            }

            bufferedWriter.write(entry.getKey() + " -> value: " + entry.getValue().toString() + "\n\n");

        }

        bufferedWriter.close();
        outputStream.close();
    }

    public static Map<String, String> extractKeyParam(String param) {
        List<String> paramList = Arrays.asList(param.split("&"));
        Map<String, String> paramMap = new HashMap<>();
        for (String pa : paramList) {
            String[] paArr = pa.split("=");
            String key = paArr[0];
            String value = paArr[1];
            if (key.equals("payType") || key.equals("payMode") || key.equals("appName") || key.equals("merchantId") ||
                    key.equals("subMerchantId") || key.equals("bizMerchantNo") || key.equals("bizSubMerchantNo")) {
                paramMap.put(key, value);
            }
        }

        return paramMap;
    }

    public static void processLine(Map<String, String> dicMap) throws Exception {
        // start to load file to memory
        Map<String, String> map = new TreeMap<>();
        String line = null;
        try {
            FileInputStream inputStream = new FileInputStream("/Users/vonmax/Downloads/inputFile.txt");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            String lineBefore = "", beforeBefore;
            HashSet<String> li = new HashSet<>();
            while ((line = bufferedReader.readLine()) != null) {
                beforeBefore = lineBefore;
                lineBefore = line;

                try {
                    if (line.contains("mc.appConfigMap.put")) {
                        String appName = line.split(", AppConfig.")[1].split("\\)")[0];
                        li.add(appName);
                        //System.out.println(line);
                    }


                } catch (Exception e) {
                    System.out.println("exception : " + line);
                }
            }


            for (Map.Entry<String, String> entry : dicMap.entrySet()) {
                String curStr = entry.getValue().trim();
                if (li.contains(curStr)) {
                    System.out.println(curStr+"-> 1216845401");
                } else {
                    System.out.println(curStr+"");
                }
            }


//
//            FileOutputStream outputStream = new FileOutputStream("/Users/vonmax/Downloads/fileListResult.txt");
//            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
//            for (Map.Entry<String, String> entry : map.entrySet()) {
//                bufferedWriter.write(entry.getKey() + "\n");
//            }

            //close stream
            inputStream.close();
            bufferedReader.close();
        } catch (Exception e) {
            System.out.println(line);
            e.printStackTrace();
        }


    }

    /**
     * 重新创建新Excel文件
     *
     * @return
     */
    public static String createNewExcel(List<List<String>> objList, String[] title, String filePath) {
        try {

            // 创建Excel的工作书册 Workbook,对应到一个excel文档
            XSSFWorkbook wb = new XSSFWorkbook();
            // 创建Excel的工作sheet,对应到一个excel文档的tab
            XSSFSheet sheet = wb.createSheet("sheet1");
            sheet.setColumnWidth(0, 5500);// 设置单元格宽度，这里设置第一列的宽度
            XSSFRow firstRow = sheet.createRow(0);
            // 设置字体
            XSSFFont font = wb.createFont();
            font.setBold(true);// 粗体字
            font.setFontName("宋体");
            // 设置单元格属性
            CellStyle cellStyle = wb.createCellStyle();
            cellStyle.setFont(font);// 设置字体
            // 生成表头
            for (int i = 0; i < title.length; i++) {
                XSSFCell cell = firstRow.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(cellStyle);// 设置单元格背景
            }
            // 生成数据
            for (int i = 0; i < objList.size(); i++) {
                List<String> lineObj = objList.get(i);
                XSSFRow row = sheet.createRow(i + 1);// 因为表头已经占用了第一行，所以后面生成的行需从第二行开始
                try {

                    for (int j = 0; j < lineObj.size(); j++) {
                        XSSFCell cell = row.createCell(j);
                        cell.setCellValue(lineObj.get(j).toString());
                    }
                } catch (Exception e) {
                    System.out.println("write line exception: " + lineObj.toString());
                }
            }
            FileOutputStream os = new FileOutputStream(filePath);
            wb.write(os);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void processLineDict(String fileName) throws Exception {
        // start to load file to memory
        Map<String, String> map = new TreeMap<>();
        String line = null;
        try {
            FileInputStream inputStream = new FileInputStream("/Users/vonmax/Downloads/inputFile.txt");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            String lineBefore = "", beforeBefore;
            HashSet<String> li = new HashSet<>();
            while ((line = bufferedReader.readLine()) != null) {
                beforeBefore = lineBefore;
                lineBefore = line;

                try {
                    if (line.contains("mc.appConfigMap.put")) {
                        String appName = line.split(", AppConfig.")[1].split("\\)")[0];
                        li.add(appName);
                        //System.out.println(line);
                    }


                } catch (Exception e) {
                    System.out.println("exception : " + line);
                }
            }




            //close stream
            inputStream.close();
            bufferedReader.close();
        } catch (Exception e) {
            System.out.println(line);
            e.printStackTrace();
        }


    }


    public static void main(String[] args) throws Exception {

        processLineDict("");

    }


}

